import routesList, { IRouteWithBreambItem } from "@/configs/routes"
import withBreadcrumbs, {
  BreadcrumbsRoute,
} from "react-router-breadcrumbs-hoc" // 这个插件只需要路由保持父级嵌套关系就可以
import { Link, IRoute } from "umi"
import { useLocation, useHistory } from "react-router"

/* 
此项目暂时不需要用到 面包屑 不用管
可拓展性而言，面包屑和权限管理全局对象，需要后端返回， 当国际化的情况下语言前缀要加上。
{ 
  path: '/login', name:'登录', title:'登录',  meta:{key:324234}, component: '@/pages/b',breadcrumb:'菜单two/a',
} */

const excludePaths = ["/", "/zh_CN"]

const routes = routesList.find((i) => {
  return i.path === "/"
})! as BreadcrumbsRoute

// const forRoutes = (routes: IRoute[]) => {

//   routes.forEach((i: IRoute) => {
//     if (i.path) {
//       i.breadcrumb = i.name
//       if (i.routes) {
//         forRoutes(i.routes)
//       }
//     } else {
//       // 必须为每个路由加入path，可以剔除掉404。
//       if (i.type === 404) {
//         i.breadcrumb = 404
//         i.path = "/404"
//       }
//     }
//   })

// }

const routesToBreamb = (routes: IRouteWithBreambItem[]): BreadcrumbsRoute[] => {
  const dfs = (datas: IRouteWithBreambItem[]) => {
    return datas.map((el: IRouteWithBreambItem) => {
      if (el.path) {
        el.breadcrumb = el.name
        el.routes?.length && dfs(el.routes)
      } else {
        if (el.type === 404) {
          el.breadcrumb = 404
          el.path = "/404"
        }
      }
      return el
    })
  }
  return dfs(routes) as BreadcrumbsRoute[]
}

// forRoutes(routes.routes)

const linkFn = (bc: any) => {
  const { pathname } = useLocation()
  if (bc.key !== pathname) {
    return (
      <Link
        to={{
          pathname: bc.match.url,
          state: bc.match.params ? bc.match.params : {},
          search: bc.location.query ? bc.location.query : {},
        }}
      >
        {bc.breadcrumb}
      </Link>
    )
  } else {
    return <span style={{ color: "rgb(101 95 95)" }}>{bc.breadcrumb}</span>
  }
}

const Breadcrumbs = (obj: any) => {
  const { breadcrumbs } = obj

  // console.log(breadcrumbs);

  return (
    // { const {breadcrumbs}=obj}
    <div style={{ color: "#bfbcbc" }}>
      {breadcrumbs.map((bc: any, index: number) => (
        <span key={bc.match.url}>
          {/* <Link
            style={{ color: 'rgb(101 95 95)' }}
            to={{
              pathname: bc.match.url,
              state: bc.match.params ? bc.match.params : {},
              query: bc.location.query ? bc.location.query : {},
            }}
          >
            {bc.breadcrumb}
          </Link> */}

          {linkFn(bc)}

          {index < breadcrumbs.length - 1 && <i>&nbsp;/&nbsp;</i>}
        </span>
      ))}
    </div>
  )
}

export default withBreadcrumbs(routes.routes, { excludePaths })(Breadcrumbs)
